
import time from 'locutus/php/datetime/time';

const { action } = jinghuan.props;


/**
 * 供应商
 */
class supply extends jinghuan.AdminController {

    /**
     *
     * @return {QueryBuilder}
     * @private
     */
    _listModel(id = 0) {
        let model = this.db('jh_supply')
            .where('status', '>', 0);

        if (id) {
            model.where('id', id).first()
        }

        return model;
    }

    /**
     * 
     */
    @action({ auth: false, login: false })
    async datatable() {
        let model1 = this._listModel();

        let model2 = this.db('jh_supply')
            .where('status', '>', 0)
            .count('id as count');

        await this.default_datatable2(model1, model2, [])
    }

    @action({ auth: false, login: false })
    async get_supply() {
        let data = await this.db('jh_supply')
            .select('id as value', 'name as title')

        this.callback(data);
    }

    @action({ auth: false })
    async do_add({ }, { id, name, code, phone, address, contact, position, fax, zip_code, ein, bank, bankcard, email, www, content }) {
        let model = await this.db('jh_supply')
            .insert({
                name,
                code,
                phone,
                address,
                contact,
                position,
                fax,
                zip_code,
                ein, bank,
                bankcard,
                email,
                www,
                content,
                time: time(),
                u_time: time()
            });
        if (model) {
            this.record('添加供应商成功');
            let data = await this._listModel(model[0]);
            this.callback(data, { toast: "message.success.add" });
        } else {
            this.record('添加供应商失败');
            this.callback(false, { toast: "message.error.add" });
        }
    }

    @action({ auth: false })
    async do_edit(GET, { id, name, code, phone, address, contact, position, fax, zip_code, ein, bank, bankcard, email, www, content }) {
        let model = await this.db('jh_supply')
            .where('id', '=', id)
            .update({
                name,
                code,
                phone,
                address,
                contact,
                position,
                fax,
                zip_code,
                ein, bank,
                bankcard,
                email,
                www,
                content,
                u_time: time()
            });

        if (model) {
            this.record('编辑供应商成功');
            let data = await this._listModel(id);
            this.callback(data, { toast: "message.success.edit" });
        } else {
            this.record('编辑供应商失败');
            this.callback(false, { toast: "message.error.edit" });
        }
    }

}

export default supply;